/*提示框变量*/
var layerLoad=null;
var layerNumber=null;
/* 页面初始化加载 */
(function(){
	initSysProductCategoryList(1);
})();
function initSysProductCategoryList(currentPage){
	$.ajax({
		url : $api.productCategory.selectProductCategorys,
		type : "GET",
		dataType : "JSON",
		beforeSend : function () {
			layerLoad = layer.load();
		},
		success : function(data) {
			if(!$checkRemouteStatus(data)){
				layer.close(layerLoad);
				return;
			}
			layui.use('laytpl', function() {
				var laytpl = layui.laytpl;
				laytpl(systemProductCategoryListTpl.innerHTML).render(data, function(html) {
					$('#system-product-category-list-body').html(html)
				});
			});
			layui.use('laypage', function() {
				layui.laypage({
					cont: $('#sys-product-list-body-page'),
					pages: data.totalPage,
					groups: 2,
					curr: data.currentPage,
                    skin:'#0e90d2',
					skip: true,
					jump: function (obj,first) {
						if(!first){
							initSysProductCategoryList(obj.curr);
						}
					}
				});
			});
			layer.close(layerLoad);
		},
		error : function() {
			layer.close(layerLoad);
			layer.msg('网络异常，请稍后再试', {icon: 2});
		}
	});
};
/* 详情查询 */
$('#system-product-category-list-body').on('click','.btn-system-product-category-update',function(){
    requestUrl = $api.productCategory.updateForProductCategory;
	$.ajax({
		url : $api.productCategory.selectProductCategoryById,
		type : "GET",
		dataType : "JSON",
		data : {
			"productCategoryId" : $(this).attr('id')
		},
		beforeSend : function () {
			layerLoad = layer.load();
		},
		success : function(data,e) {
			if(!$checkRemouteStatus(data)){
				layer.close(layerLoad);
				return;
			}
			var dataObj = data.msg;
			$("#name").val(dataObj.name);
			$("#englishName").val(dataObj.englishName);
			$("#productCategoryId").val(dataObj.id);
			if(dataObj.categoryImg){
				$("#categoryImg").attr("src",dataObj.categoryImg);
				$("#categoryImg").attr("flagImg", dataObj.id);
			}
			layer.close(layerLoad);
		},
		error : function() {
			layer.close(layerLoad);
			layer.msg('网络异常，请稍后再试', {icon: 2});
		}
	});
	layerNumber = layer.open({
		type : 1,
		title : '编辑商品分类',
		area : 'auto',
		maxWidth : '1000px',
		content : $('#system-product-category-update-model'),
		cancel : function(){
			$('#sys-product-form-update')[0].reset();
		}
	});
});
/*禁用*/
var enableBox;
$('#system-product-category-list-body').on('click','.enable',function(){
	var idTxt=$(this).attr('id');
	var orders;
    var ordersTxt;
    console.log($(this).val());
    $(this).val() === "禁用"?orders=1 : orders=0;//1是禁用
    orders === 1 ? ordersTxt="禁用分类后，该分类下商品均会下架，是否禁用？":ordersTxt="启用分类后，该分类下商品均会上架，是否启用？"
    $.ajax({
        url : $api.productCategory.checkProductCategoryCanForbidden,
        type : "GET",
        dataType : "JSON",
        data : {
            "productCategoryId" :idTxt
        },
        beforeSend : function () {
            layerLoad = layer.load();
        },
        success : function(data,e) {
            if(!$checkRemouteStatus(data)){
                layer.close(layerLoad);
                return;
            }else{
                enableBox=layer.confirm(ordersTxt, {
                    btn: ['确定', '取消'],btn2:
					function(index, layero){
                    }},
					function(index, layero){
                    forbiddenProductCategory(idTxt,orders);
                },
					function(index){
                    //按钮【按钮二】的回调
                });}
            layer.close(layerLoad);
        },
        error : function() {
            layer.close(layerLoad);
            layer.msg('网络异常，请稍后再试', {icon: 2});
        }
    });
});
function forbiddenProductCategory(idTxt,orders){
    $.ajax({
        url : $api.productCategory.forbiddenProductCategory,
        type : "GET",
        dataType : "JSON",
        data : {
            "productCategoryId" : idTxt,
			"orders":orders
        },
        beforeSend : function () {
            layerLoad = layer.load();
        },
        success : function(data,e) {
            if(!$checkRemouteStatus(data)){
                layer.close(layerLoad);
                return;
            }else{
                layer.close(enableBox);
                layer.msg(data.msg,{icon:1});
                initSysProductCategoryList(1);
            }
            layer.close(layerLoad);
        },
        error : function() {
            layer.close(layerLoad);
            layer.msg('网络异常，请稍后再试', {icon: 2});
        }
    });
}
/*图片转64*/
window.onload = function(){
    var input = document.getElementById("productFileImg");
    if ( typeof(FileReader) === 'undefined' ){
    	layer.msg("抱歉，你的浏览器不支持 FileReader，请使用现代浏览器操作！", {icon: 2});
        input.setAttribute( 'disabled','disabled' );
    } else {
        input.addEventListener( 'change',readFile,false );}
};
function readFile(){
    var file = this.files[0];
    var productImg=$("#categoryImg");
    //这里我们判断下类型如果不是图片就返回 去掉就可以上传任意文件
    if(!/image\/\w+/.test(file.type)){
    	layer.msg("仅支持图片上传", {icon: 2});
        return false;
    }
    var reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = function(e){
		//验证
		if(file.size/1024>20){	//图片大小限制
			layer.msg("图片不得大于20K.....", {icon: 2});
			return
			}
		$(productImg).attr("src",this.result);
		$(productImg).attr("flagImg", "-1");
        $("#productFileImg").val("");
    }
};
/*新增*/
$("#product-category-add").on("click", function(){
    requestUrl = $api.productCategory.insertProductCategory;
    $("#categoryImg").attr("flagImg","0");
    $("#categoryImg").attr("src","");
    /*清空*/
    $("#categoryImg").attr("src","");
	layerNumber=layer.open({
		type : 1,
		title : '新增商品分类',
		area : 'auto',
		maxWidth : '1000px',
		content : $('#system-product-category-update-model'),
		cancel : function(){
			$('#sys-product-form-update')[0].reset();
		}
	});
});
var requestUrl = "";
/*保存*/
$("#save").click(function(){
    if($("#categoryImg").attr("flagImg")==="0"){
        layer.msg("请选择正确的分类图片", {icon: 2});
        return false;
    }
    var ajaxFlag=1;
    $("#sys-product-form-update input[required='required']").each(function(index,dom){
        if($(dom).val()===""){
            $(dom).addClass("am-field-error");
            layer.msg("信息填写不完整，请检查", {icon: 2});
            ajaxFlag=0;
            return false;
        }
    });
    if(ajaxFlag==0){
        return false;
    }
    var productData={};
    productData["id"]=$("#productCategoryId").val();
    productData["name"]=$("#name").val();
    productData["englishName"]=$("#englishName").val();
    productData["base64String"]=$("#categoryImg").attr("src");
    productData["isNew"]=$("#categoryImg").attr("flagImg");
    $.ajax({
        url: requestUrl,
        type: "POST",
        dataType: "JSON",
        contentType : 'application/json',
        data :  JSON.stringify(productData) ,
        beforeSend: function () {
            layerLoad = layer.load();
        },
        success: function (data) {
            layer.close(layerLoad);
            var dataObj=data.msg;
            if(data.code == '111111'){
                layer.msg(data.msg, {icon: 2});
            }else{
                layer.msg(data.msg, {icon: 1});
                initSysProductCategoryList(1);
                layer.close(layerNumber);
                $("#categoryImg").attr("src","");
                $("#englishName").val("");
                $("#name").val("");
            }
        },
        error: function () {
            layer.msg("网络开小差啦", {icon: 2});
        }
    });
});